const { getType, isEmptyObject } = require("../utils")
const { decrypt } = require("../utils/crypto")

module.exports = options => {
    return async (req, res, next) => {
        // 将categories ==> Category
        if (!req.params.resource) {
            return next()
        }
        const modelName = require("inflection").classify(req.params.resource)
        req.Model = require(`../models/${modelName}`)
        delete req.params.resource;
        let method = !isEmptyObject(req.body) ? 'body'
            : !isEmptyObject(req.query) ? 'query'
                : !isEmptyObject(req.params) ? 'params'
                    : null;
        if (req.Model.modelName === "User") {
            let newUser = {};
            if (method) {
                Object.keys(req[method]).forEach(key => {
                    if (key === "password" || key === 'username') {
                        newUser[key] = decrypt(req[method][key])
                    } else {
                        newUser[key] = req[method][key];
                    }
                })
            }
            req[method] = newUser;
        }
        if (req.Model.modelName === "Camera") {
            let newCamera = {};
            if (method) {
                Object.keys(req[method]).forEach(key => {
                    if (['host', 'username', 'password'].includes(key)) {
                        newCamera[key] = decrypt(req[method][key])
                    } else {
                        newCamera[key] = req[method][key];
                    }
                })
            }
            req[method] = newCamera;
        }
        next()
    }
}
